package top.xiaozhaobk.xiaofenshu.auth.service.impl;

import ch.qos.logback.core.testUtil.RandomUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Service;
import top.xiaozhaobk.framework.common.exception.BizException;
import top.xiaozhaobk.framework.common.response.Response;
import top.xiaozhaobk.xiaofenshu.auth.constant.RedisKeyConstants;
import top.xiaozhaobk.xiaofenshu.auth.enums.ResponseCodeEnum;
import top.xiaozhaobk.xiaofenshu.auth.model.vo.verificationcode.SendVerificationCodeReqVO;
import top.xiaozhaobk.xiaofenshu.auth.service.VerificationCodeService;
import top.xiaozhaobk.xiaofenshu.auth.sms.AliyunSmsHelper;

import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {
    @Resource
    private RedisTemplate<String,Object> redisTemplate;
    @Resource
    private ThreadPoolTaskExecutor taskExecutor;
    @Resource
    private AliyunSmsHelper aliyunSmsHelper;

    /**
     * 发送验证码
     *
     * @param reqVO
     * @return
     */
    @Override
    public Response<?> send(SendVerificationCodeReqVO reqVO) {
        String phone = reqVO.getPhone();
        // 生成验证码
        String key = RedisKeyConstants.buildVerificationCodeKey(phone);
        if (Boolean.TRUE.equals(redisTemplate.hasKey(key))){
            throw new BizException(ResponseCodeEnum.VERIFICATION_CODE_SEND_FREQUENTLY);
        }


        // 生成六位随机验证码
        String verificationCode = String.valueOf(RandomUtils.nextInt(100000, 999999));
        // 发送验证码
        taskExecutor.submit(() -> {
            String signName = "阿里云短信测试";
            String templateCode = "SMS_154950909";
            String templateParam = String.format("{\"code\":\"%s\"}", verificationCode);
            aliyunSmsHelper.sendMessage(signName, templateCode, phone, templateParam);
        });

        log.info("==> 手机号: {}, 已发送验证码：【{}】", phone, verificationCode);
        redisTemplate.opsForValue().set(key,verificationCode,60, TimeUnit.MINUTES);

        return Response.success();
    }
}
